const Router = require('koa-router')
const { ArticleInfo } = require('../../schedma/db')
const router = new Router()

router.post('/write/article', async (ctx) => {
  const article = new ArticleInfo({
    username: ctx.user.name,
    title: ctx.request.body.title,
    content: ctx.request.body.content,
    createOn: new Date(),
    isTop: ctx.request.body.isTop || false
  })
  const data = await article.save()
  if (data) {
    ctx.body = true
  } else {
    ctx.body = {
      code: 500,
      message: '保存失败'
    }
  }
})

router.put('/write/article', async (ctx) => {
  const id = ctx.request.body.id
  const data = await ArticleInfo.updateOne({_id: id}, {$set: ctx.request.body})
  ctx.body = {
    data,
    message: 'success'
  }
})

router.get('/article/list', async (ctx) => {
  const page = +ctx.request.query.curPage
  const pageSize = +ctx.request.query.pageSize
  const length = await ArticleInfo.countDocuments()
  const data_isTop = await ArticleInfo.find({isTop: true}, { _id: 1, title: 1, createOn: 1, username: 1, isTop: 1}).sort({'_id': -1}).skip((page - 1) * pageSize).limit(pageSize)
  const data_isNotTop = await ArticleInfo.find({isTop: false}, { _id: 1, title: 1, createOn: 1, username: 1, isTop: 1}).sort({'_id': -1}).skip((page - 1) * pageSize).limit(pageSize)
  const data_isNotTopOrigin = await ArticleInfo.find({isTop: null}, { _id: 1, title: 1, createOn: 1, username: 1, isTop: 1}).sort({'_id': -1}).skip((page - 1) * pageSize).limit(pageSize)
  const data = data_isTop.concat(data_isNotTop, data_isNotTopOrigin)
  ctx.body = {
    items: data,
    page: {
      total: length,
      page,
      pageSize
    }
  }
})

router.get('/article/detail/:id', async (ctx) => {
  const id = ctx.params.id
  const data = await ArticleInfo.findOne({_id: id})
  ctx.body = data
})

module.exports = router